//
//  CYPickerDatasourceDelegate.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/11.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYPickerDatasourceDelegate.h"
#import "CYTime.h"
@interface CYPickerDatasourceDelegate(){
    pickerDatasourceBlock _myblock;
}
@property (nonatomic, strong) NSMutableArray *source;  //数据源

@property (nonatomic, strong) NSMutableArray *minuteArr;
@property (nonatomic, strong) NSMutableArray *hourArr;
@property (nonatomic, strong) NSMutableArray *dayArr;
@property (nonatomic, strong) NSMutableArray *monthArr;
@property (nonatomic, strong) NSMutableArray *yearArr;
@property (nonatomic, strong) NSArray *currentArr;

@property (nonatomic, strong) NSMutableArray *districtArr;
@property (nonatomic, strong) NSMutableArray *cityArr;
@property (nonatomic, strong) NSMutableArray *provinceArr;
@property (nonatomic, strong) NSDictionary *provinceDic;
@property (nonatomic, strong) NSDictionary *allAreaDic;
@end
@implementation CYPickerDatasourceDelegate
- (instancetype)initWithDidSelct:(pickerDatasourceBlock)block{
self = [super init];
    if (self) {
        _myblock = block;
        self.CYPickerDataSource = self;
        self.CYPickerDelegate = self;
    }
    return self;
}

//根据是日期还是地区，更换数据源
- (void)setType:(PickerType)type{
    if (_type != type)
        _type = type;
    self.source = (type == datePicker)?[NSMutableArray  arrayWithObjects:self.monthArr, self.dayArr, self.hourArr, self.minuteArr, nil]:[NSMutableArray arrayWithObjects:self.provinceArr, self.cityArr, self.districtArr, nil];
}
- (void)setSource:(NSMutableArray *)source{
    if (_source != source)
        _source = source;
    _myblock(nil);
    
}

#pragma mark - UIPickerViewDataSource 数据源方法
// 返回多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return _source.count;
}

// 返回多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [_source[component]count];
}

#pragma mark - UIPickerViewDelegate 代理方法
// 返回每行的标题
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    [self didSelectString:pickerView];
    return _source[component][row];
}

// 选中行显示在label上
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (_type == datePicker) {//时间联动
        if ([self isPastTime:pickerView component:component]) //如果是过去时间
            [self scrollToCurrentTime:pickerView component:component];
    }
    else if (_type == areaPicker)//地区联动
        [self linkageRefresh:pickerView row:row comonent:component];//
    [self didSelectString:pickerView];
    return;
}

//pickerview row显示的label
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    CYLabel *label = [[CYLabel alloc]initWithText:_source[component][row] size:AL(PT(30)) textcolor:ColorHex(0x000000)];
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

#pragma - mark CYPickerDatasourceDelegate - Methods
//判断选择的时间是否小于当前的时间
- (BOOL)isPastTime:(UIPickerView *)pickerView component:(NSUInteger)component{
    
    for (int i = 0; i <= component; i ++) {
        int current_time = [self.currentArr[i] intValue]; //获取当前月／日／时／分
        int row = (int)[pickerView selectedRowInComponent:i];//对应component，选中的row
        int select_time = [_source[i][row] intValue];    //选中的时间
        if (select_time > current_time && i <= component)
            return NO;
    }
    return YES;
}

//如果选择时间小于当前时间，滚回当前时间(如果最大单位-月份大于当前月份，则日/时/分都可以小于当前时间)
- (void)scrollToCurrentTime:(UIPickerView *)pickerView component:(NSUInteger)component{
    for (int i = (int)component; i < self.currentArr.count; i ++) {
        int current_time = [self.currentArr[i] intValue]; //获取当前月／日／时／分
        if (i < 2)//月／日
            [pickerView selectRow:(NSUInteger)current_time - 1 inComponent:i animated:YES];//月份的初始值为1月，日的初始值为1日，如果选择当前时间以前的时间，会自动滚动到当前时间
        else//时／分
            [pickerView selectRow:(NSUInteger)current_time inComponent:i animated:YES];//时间的初始值为0时，分的初始值位0分，如果选择当前时间以前的时间，会自动滚动到当前时间
    }
    
}


//滚动到不同的省份，或者市级，替换下面相应的行政区的资料。实现联动
- (void)linkageRefresh:(UIPickerView *)pickerView row:(NSUInteger)row comonent:(NSUInteger)component{
    if (component == 0) {//滚动的是省份
        _provinceDic = [self getSubData:_allAreaDic index:row];//获取省级地区资料
        [_source replaceObjectAtIndex: 1 withObject:[self getCityArray:row]];//替换市级资料
        [_source replaceObjectAtIndex: 2 withObject:[self getDistrictArr:_provinceDic cityIndex:0]];//替换区级资料
        [pickerView reloadAllComponents];
        [pickerView selectRow:0 inComponent:1 animated:YES];//显示当前省份的第一个市
        [pickerView selectRow:0 inComponent:2 animated:YES];//显示当前省份的第一个市的第一个区
    }
    else if (component == 1){//滚动的是市区
        [_source replaceObjectAtIndex:2 withObject:[self getDistrictArr:_provinceDic cityIndex:row]];
        [pickerView reloadAllComponents];
        [pickerView selectRow:0 inComponent:2 animated:YES];//显示当前省份的第一个市的第一个区
    }
    
}

//当前选择的时间／地区
- (void)didSelectString:(UIPickerView *)pickerView{
    NSMutableString *string = [NSMutableString string];//拼接
    for (int i = 0; i < _source.count; i ++) {
        int row = (int)[pickerView selectedRowInComponent:i];
        [string appendString:_source[i][row]];//拼接时间/地址
    }
    _myblock((NSString *)string);//选中的字符串
}
#pragma - mark end

#pragma - mark 懒加载
//获取当前的月日时分
- (NSArray *)currentArr{
    if (!_currentArr)
        _currentArr = [CYTime timeArray];
    return _currentArr;
}

- (NSMutableArray *)minuteArr{
    if (!_minuteArr) {
        _minuteArr= [NSMutableArray array];
        for (int i = 0; i < 60; i++) {
            [_minuteArr addObject:[NSString stringWithFormat:@"%d分",i]];
        }
        return _minuteArr;
    }
    return _minuteArr;
}

- (NSMutableArray *)hourArr{
    if (!_hourArr) {
        _hourArr = [NSMutableArray array];
        for (int i = 0; i < 24; i ++) {
            [_hourArr addObject:[NSString stringWithFormat:@"%d时", i]];
        }
    }
    return _hourArr;
}

- (NSMutableArray *)dayArr{
    if (!_dayArr) {
        _dayArr = [NSMutableArray array];
        for (int i = 1; i < 32; i ++) {
            [_dayArr addObject:[NSString stringWithFormat:@"%d日",i]];
        }
    }
    return _dayArr;
}

- (NSMutableArray *)monthArr{
    if (!_monthArr) {
        _monthArr = [NSMutableArray array];
        for (int i = 1; i < 13; i ++) {
            [_monthArr addObject:[NSString stringWithFormat:@"%d月",i]];
        }
    }
    return _monthArr;
}

//获取所有的省级名称
- (NSMutableArray *)provinceArr{
    if (!_provinceArr)
        _provinceArr = [self getNames:self.allAreaDic];
    return _provinceArr;
}

//默认第一次获取北京市城市名称集合
- (NSMutableArray *)cityArr{
    if (!_cityArr)
        _cityArr = [self getCityArray:0];
    return _cityArr;
}

//默认第一次获取北京市地区名称集合
- (NSMutableArray *)districtArr{
    if (!_districtArr)
        _districtArr = [self getDistrictArr:[self getSubData:_allAreaDic index:0] cityIndex:0];
    return _districtArr;
}

//根据省级坐标，获得省辖区所有市级的名称
- (NSMutableArray *)getCityArray:(NSUInteger)provinceIndex{
    
    NSDictionary *provinceDic = (NSDictionary *)[self getSubData:_allAreaDic index:provinceIndex];
    return  [self getNames:provinceDic];
}

//根据省级字典，市级坐标，获得市辖区所有区级名称
- (NSMutableArray *)getDistrictArr:(NSDictionary *)dict cityIndex:(NSUInteger)index{
    
    NSMutableArray *array = (NSMutableArray *)[self getSubData:dict index:index];
    return array;
}


//获取省级字典，市级数组
- (id)getSubData:(NSDictionary *)dict index:(NSUInteger)index{
    
    NSDictionary *indexDic = [dict objectForKey:[@(index) stringValue]];
    NSString *areaName =[self getSubName:dict index:index];
    id newDic = [indexDic objectForKey:areaName];
    return   newDic;
}

//获取某个行政区的名称，比如，获取湖南省名称，深圳市名称，龙岗区名称
- (NSString *)getSubName:(id)data index:(NSUInteger)index{
    if ([data isKindOfClass:[NSDictionary class]])
        return [[[(NSDictionary *)data objectForKey:[@(index) stringValue]] allKeys] firstObject];
    else if ([data isKindOfClass:[NSString class]])
        return (NSString *)data;
    return nil;
}
//获取省/市两级，所有的名称，
- (NSMutableArray *)getNames:(NSDictionary *)dict{
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < dict.count; i ++) {
        [array addObject:[self getSubName:dict index:i]];
    }
    return array;
}
//读取行政区数据
- (NSDictionary *)allAreaDic{
    if (!_allAreaDic) {
        NSBundle *bundle=[NSBundle mainBundle];
        NSString *path=[bundle pathForResource:@"city" ofType:@"plist"];
        _allAreaDic = [[NSDictionary alloc]initWithContentsOfFile:path];
    }
    return _allAreaDic;
}


//- (NSUInteger)judgeFebruay{
//    NSArray *days = @[@"31", @"28", @"31", @"30", @"31", @"30", @"31", @"31", @"30", @"31", @"30", @"31"];
//
//    if (2 == [_source[0] integerValue] && 0 == (year % 4) && (0 != (year % 100) || 0 == (year % 400))) {
//        return 29;
//    }
//    return days[month - 1];


//}
@end
